<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import { RouterLink } from "vue-router"
import { Star, StarFilled } from '@element-plus/icons-vue'
import { useToolsStore } from '@/store/modules/tools'
// import { ElMessage } from 'element-plus'
import { useRoute } from "vue-router"
//store
const toolsStore = useToolsStore()
const route = useRoute()

// 本地缓存喜欢的工具url
const FAVORITE_KEY = 'yy_favorite_tools'
const favoriteUrls = ref<string[]>([])

function loadFavorite() {
  const raw = localStorage.getItem(FAVORITE_KEY)
  favoriteUrls.value = raw ? JSON.parse(raw) : []
}
function saveFavorite() {
  localStorage.setItem(FAVORITE_KEY, JSON.stringify(favoriteUrls.value))
}
function toggleFavorite(url: string) {
  const idx = favoriteUrls.value.indexOf(url)
  if (idx === -1) {
    favoriteUrls.value.push(url)
  } else {
    favoriteUrls.value.splice(idx, 1)
  }
  saveFavorite()
}
function isFavorite(url: string) {
  return favoriteUrls.value.includes(url)
}

// 计算"我的喜欢"工具
const myFavoriteList = computed(() => {
  const all = toolsStore.cates.flatMap(cate => cate.list)
  return all.filter(item => isFavorite(item.url))
})

// 浅渐变暖色系配色方案
const warmColors = [
  { bg: 'linear-gradient(135deg, #FFF8F0 0%, #FFE8D5 100%)', border: '#FFE8D5', shadow: '#FFD4A3' },  // 橙色渐变
  { bg: 'linear-gradient(135deg, #FFF5F5 0%, #FFE3E3 100%)', border: '#FFE3E3', shadow: '#FFB8B8' },  // 红色渐变
  { bg: 'linear-gradient(135deg, #FFFEF0 0%, #FFF4C6 100%)', border: '#FFF4C6', shadow: '#FFE88A' },  // 黄色渐变
  { bg: 'linear-gradient(135deg, #FFF5FA 0%, #FFE3EE 100%)', border: '#FFE3EE', shadow: '#FFADD2' },  // 粉色渐变
  { bg: 'linear-gradient(135deg, #FFFAFC 0%, #FFF0F6 100%)', border: '#FFF0F6', shadow: '#FFB8D2' },  // 玫瑰渐变
  { bg: 'linear-gradient(135deg, #FFFAF5 0%, #FFEBD9 100%)', border: '#FFEBD9', shadow: '#FFD1A3' },  // 桃色渐变
  { bg: 'linear-gradient(135deg, #FFF6F5 0%, #FFE0D9 100%)', border: '#FFE0D9', shadow: '#FFC4B8' },  // 珊瑚渐变
  { bg: 'linear-gradient(135deg, #FFFCF5 0%, #FFF2D9 100%)', border: '#FFF2D9', shadow: '#FFD9A3' },  // 琥珀渐变
  { bg: 'linear-gradient(135deg, #FFF0F8 0%, #FFD6EC 100%)', border: '#FFD6EC', shadow: '#FFB3D9' },  // 樱花渐变
  { bg: 'linear-gradient(135deg, #FFF8F3 0%, #FFEADC 100%)', border: '#FFEADC', shadow: '#FFD2B3' },  // 杏色渐变
  { bg: 'linear-gradient(135deg, #FFF9F0 0%, #FFECD5 100%)', border: '#FFECD5', shadow: '#FFD4A8' },  // 蜜色渐变
  { bg: 'linear-gradient(135deg, #FFF5F8 0%, #FFE0E9 100%)', border: '#FFE0E9', shadow: '#FFBFD1' },  // 莓色渐变
  { bg: 'linear-gradient(120deg, #FFF9F0 0%, #FFD6A5 100%)', border: '#FFD6A5', shadow: '#FFB366' },  // 杏橙渐变
  { bg: 'linear-gradient(120deg, #FFF0F9 0%, #FFDAE6 100%)', border: '#FFDAE6', shadow: '#FFB3CC' },  // 粉玫渐变
  { bg: 'linear-gradient(120deg, #FFFBF0 0%, #FFE599 100%)', border: '#FFE599', shadow: '#FFD666' },  // 金黄渐变
  { bg: 'linear-gradient(120deg, #FFF6F0 0%, #FFD9C7 100%)', border: '#FFD9C7', shadow: '#FFB899' },  // 奶橙渐变
  { bg: 'linear-gradient(120deg, #FFF5F9 0%, #FFDDE8 100%)', border: '#FFDDE8', shadow: '#FFB8CC' },  // 浅粉渐变
  { bg: 'linear-gradient(120deg, #FFFDF0 0%, #FFEBAD 100%)', border: '#FFEBAD', shadow: '#FFDA70' },  // 明黄渐变
  { bg: 'linear-gradient(45deg, #FFF5F5 0%, #FFDADA 100%)', border: '#FFDADA', shadow: '#FFB8B8' },   // 淡红渐变
  { bg: 'linear-gradient(45deg, #FFF8F5 0%, #FFE3D5 100%)', border: '#FFE3D5', shadow: '#FFC7A8' },   // 肉桃渐变
  { bg: 'linear-gradient(45deg, #FFF9F5 0%, #FFDDCC 100%)', border: '#FFDDCC', shadow: '#FFB899' },   // 蜜桃渐变
  { bg: 'linear-gradient(45deg, #FFF5F7 0%, #FFD9E5 100%)', border: '#FFD9E5', shadow: '#FFB3CC' },   // 樱粉渐变
  { bg: 'linear-gradient(45deg, #FFFAF5 0%, #FFE0C7 100%)', border: '#FFE0C7', shadow: '#FFC299' },   // 奶茶渐变
  { bg: 'linear-gradient(45deg, #FFF7F5 0%, #FFD6CC 100%)', border: '#FFD6CC', shadow: '#FFB8A8' },   // 珊瑚粉渐变
  { bg: 'linear-gradient(60deg, #FFF9F8 0%, #FFE0D9 100%)', border: '#FFE0D9', shadow: '#FFC2B3' },   // 浅珊瑚渐变
  { bg: 'linear-gradient(60deg, #FFFBF5 0%, #FFE8C7 100%)', border: '#FFE8C7', shadow: '#FFD199' },   // 奶黄渐变
  { bg: 'linear-gradient(60deg, #FFF5F6 0%, #FFD9DF 100%)', border: '#FFD9DF', shadow: '#FFB8C7' },   // 粉橙渐变
  { bg: 'linear-gradient(60deg, #FFF8F9 0%, #FFE3E8 100%)', border: '#FFE3E8', shadow: '#FFCCD6' },   // 淡粉渐变
  { bg: 'linear-gradient(90deg, #FFF5F0 0%, #FFD9C7 100%)', border: '#FFD9C7', shadow: '#FFB899' },   // 暖橙渐变
  { bg: 'linear-gradient(90deg, #FFF9F7 0%, #FFE5D9 100%)', border: '#FFE5D9', shadow: '#FFCCB3' },   // 杏粉渐变
]

// 存储每个分类的颜色索引映射
const colorIndexMap = ref<Map<string, number>>(new Map())

// 获取工具颜色，确保相邻的不重复，每次刷新随机分配
function getColorForTool(url: string, itemList: any[], currentIndex: number) {
  // 如果已经为该工具分配过颜色，直接返回
  if (colorIndexMap.value.has(url)) {
    return warmColors[colorIndexMap.value.get(url)!]
  }

  // 获取相邻工具的颜色索引
  const prevIndex = currentIndex > 0 ? colorIndexMap.value.get(itemList[currentIndex - 1].url) : undefined
  const nextIndex = currentIndex < itemList.length - 1 ? colorIndexMap.value.get(itemList[currentIndex + 1].url) : undefined

  const usedIndices = new Set([prevIndex, nextIndex].filter(idx => idx !== undefined))

  // 生成可用的颜色索引列表（排除相邻已使用的）
  const availableIndices = []
  for (let i = 0; i < warmColors.length; i++) {
    if (!usedIndices.has(i)) {
      availableIndices.push(i)
    }
  }

  // 从可用颜色中随机选择一个
  const randomIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)]

  // 存储颜色索引
  colorIndexMap.value.set(url, randomIndex)
  return warmColors[randomIndex]
}

const getToolsCate = async () => {
  try {
    await toolsStore.getToolCate()
  } catch (error: any) {
    console.error('Failed to load tools:', error.message)
  }
}

onMounted(async () => {
  loadFavorite()
  await getToolsCate()
  if (route.query && route.query.value) {//底部导航跳转过来的则定位到响应位置
      document?.querySelector('#' + `${route.query.value}`)?.scrollIntoView();
  } else {//其他位置跳转过来不需要定位的则定位到顶部
      document?.querySelector('#collect')?.scrollIntoView()
  }
})
</script>

<template>
  <div class="md:mr-6 c-xs:mr-0">
    <!-- 我的喜欢 -->
    <div v-if="myFavoriteList.length">
      <div class="mt-8 mb-3 text-xl font-bold text-[--base-black]">我的喜欢</div>
      <div class="flex justify-between flex-wrap self-card-div c-xs:ml-0" :gutter="10">
        <router-link
          v-for="(item, idx) in myFavoriteList"
          :key="'fav-' + item.url"
          :to="item.url"
          class="flex flex-col mt-5 border-solid rounded-2xl w-[24%] p-2 hover:shadow-lg c-xs:w-[99.5%] c-md:w-[24%] c-sm:w-[32%] p-5 hover:-translate-y-2 duration-300 relative"
          :style="{
            background: getColorForTool(item.url, myFavoriteList, idx).bg,
            borderColor: getColorForTool(item.url, myFavoriteList, idx).border,
            borderWidth: '2px',
            boxShadow: `0 4px 6px -1px ${getColorForTool(item.url, myFavoriteList, idx).shadow}20`
          }"
        >
          <!-- 星标按钮 -->
          <el-icon class="!absolute !right-2 !top-2 !z-20 bg-white/80 rounded-full shadow p-1" :size="28" @click.stop.prevent="toggleFavorite(item.url)">
            <component :is="isFavorite(item.url) ? StarFilled : Star" :style="isFavorite(item.url) ? 'color: #f7ba2a' : 'color: #bbb'" />
          </el-icon>
          <div class="flex items-center border-b pb-2">
            <el-image :src="item.logo" class="w-10 h-10 min-h-[2.5rem] min-w-[2.5rem] rounded-full"></el-image>
            <div class="flex flex-col ml-2 w-full">
              <div class="flex">
                <div class="font-semibold text-lg line-clamp-1">{{ item.title }}</div>
              </div>
              <div class="flex justify-between">
                <el-text size="small">{{ item.cate }}</el-text>
              </div>
            </div>
          </div>
          <div class="flex items-center justify-between mt-2">
            <el-text line-clamp="2">{{ item.desc }}</el-text>
          </div>
        </router-link>
        <div class="w-[24%] c-md:w-[24%] c-sm:w-[32%] "></div>
      </div>
    </div>
    <!-- 原有分类 -->
    <div v-for="(cate, index) in toolsStore.cates" :key="index">
      <div class="mt-8 mb-3 text-xl font-bold text-[--base-black]" :id="'cate_' + cate.id">
        {{ cate.title }}
      </div>
      <div class="flex justify-between flex-wrap self-card-div c-xs:ml-0" :gutter="10">
          <router-link
            v-for="(item, idx) in cate.list"
            :key="item.url"
            :to="item.url"
            class="flex flex-col mt-5 border-solid rounded-2xl w-[24%] p-2 hover:shadow-lg c-xs:w-[99.5%] c-md:w-[24%] c-sm:w-[32%] p-5 hover:-translate-y-2 duration-300 relative"
            :style="{
              background: getColorForTool(item.url, cate.list, idx).bg,
              borderColor: getColorForTool(item.url, cate.list, idx).border,
              borderWidth: '2px',
              boxShadow: `0 4px 6px -1px ${getColorForTool(item.url, cate.list, idx).shadow}20`
            }"
          >
            <!-- 星标按钮 -->
            <el-icon class="!absolute !right-2 !top-2 !z-20 bg-white/80 rounded-full shadow p-1" :size="28" @click.stop.prevent="toggleFavorite(item.url)">
              <component :is="isFavorite(item.url) ? StarFilled : Star" :style="isFavorite(item.url) ? 'color: #f7ba2a' : 'color: #bbb'" />
            </el-icon>
            <div class="flex items-center border-b pb-2">
              <el-image :src="item.logo" class="w-10 h-10 min-h-[2.5rem] min-w-[2.5rem] rounded-full"></el-image>
              <div class="flex flex-col ml-2 w-full">
                <div class="flex">
                  <div class="font-semibold text-lg line-clamp-1">{{ item.title }}</div>
                </div>
                <div class="flex justify-between">
                  <el-text size="small">{{ item.cate }}</el-text>
                </div>
              </div>
            </div>
            <div class="flex items-center justify-between mt-2">
              <el-text line-clamp="2">{{ item.desc }}</el-text>
            </div>
          </router-link>
          <div class="w-[24%] c-md:w-[24%] c-sm:w-[32%] "></div>
      </div>
    </div>
    <!-- 返回顶部 -->
    <el-backtop :right="10" :bottom="50" />
  </div>
</template>

<style scoped>
.self-card-div:after{
  content: "";
  width: 24%
}

/* 适配顶部header/搜索栏遮挡 */
[id^='cate_'] {
  scroll-margin-top: 110px;
}
</style>
